package top.pmwly.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import top.pmwly.common.constant.ReslutEnum;
import top.pmwly.common.reslut.ReslutBean;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Herther
 * @version 1.0.0
 * @ClassName RestfulAccessDeniedHandler.java
 * @Description 当访问接口没有权限时自定义返回结果
 * @createTime 2021年09月21日 22:39:00
 */
@Component
public class RestfulAccessDeniedHandler implements AccessDeniedHandler {


    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        //设置编码
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        //输出流
        PrintWriter writer = response.getWriter();
        //结果集返回
        ReslutBean reslut = ReslutBean.FAIL(ReslutEnum.FAIL_AUTHORITY);
        //输出
        writer.println( new ObjectMapper().writeValueAsString(reslut));
        //刷新
        writer.flush();
        //关闭流
        writer.close();
    }
}
